package com.internet;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 实现TCP的网络编程
 *
 * 例题2:客户端发送文件到服务器，服务器将文件保存到本地
 */
public class TCPTest2 {


    @Test
    public void client() throws IOException {

        //1.获取Socket
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);

        //2.获取输出流
        OutputStream outputStream = socket.getOutputStream();

        //3.获取输入流
        FileInputStream fileInputStream = new FileInputStream(new File("蝙蝠侠.ico"));

        byte[] buffer = new byte[1024];
        int len;

        while ((len = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }

        fileInputStream.close();
        outputStream.close();
        socket.close();


    }


    @Test
    public void server() throws IOException {

        ServerSocket ss = new ServerSocket(9090);

        Socket socket = ss.accept();

        InputStream inputStream = socket.getInputStream();


        FileOutputStream fileOutputStream = new FileOutputStream(new File("蝙蝠侠3.ico"));

        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, len);
        }


    }




}
